<template>
	<view>
		<view class="store">
			<view class="storeDetailsBg">
				<image src="/static/storeDetailsBg.png"></image>
			</view>
			<view class="back" @click="back" :style="{top:`${menuButton.top}rpx`}">
				<uni-icons type="left" size="25" color="#fff"></uni-icons>
			</view>
			<view class="storeContent">
				<view class="storeTop">
					<view class="right">
						<view class="name">{{storeDetail.storeName}}</view>
						<view class="des">
							<!-- {{storeDetail.storeDescription}} -->
							<view class="">
								<!-- 综合评分 -->
								<uni-icons type="star-filled" size="15" color="#FF1010"></uni-icons>
								<text>{{ storeDetail.score || 0 }}分</text>
							</view>
							<view class="">
								月售{{ storeDetail.sales || 0 }}
							</view>
							<view>营业时间：{{storeDetail.businessHoursBegin || ''}}-{{storeDetail.businessHoursEnd || ''}}</view>
						</view>
						<view class="coupons">
							<view v-for="items in storeDetail.coupons" @click="claimCoupons(storeDetail,items)"
								:class="items.received ? 'received' : ''">
								{{items.couponName}}
								<text>{{items.received ? '已领取' : '领取'}}</text>
							</view>
							<!-- <view class="received">
								{{"测试测试测试测试" }}
								<text>{{ '已领取'}}</text>
							</view>
							<view class="received">
								{{"测试测试测试测试" }}
								<text>{{ '已领取'}}</text>
							</view>
							<view class="received">
								{{"测试测试测试测试" }}
								<text>{{ '已领取'}}</text>
							</view>
							<view class="received">
								{{"测试测试测试测试" }}
								<text>{{ '已领取'}}</text>
							</view>
							<view class="received">
								{{"测试测试测试测试" }}
								<text>{{ '已领取'}}</text>
							</view> -->
						</view>
					</view>

					<image class="logo" :src="storeDetail.logo"></image>
				</view>
				<view class="search">
					<view >
						<uni-icons type="search" color="#CCCCCC" size="25"></uni-icons>
					</view>
					<input v-model="keyword" placeholder="搜索商品名称" type="search" confirm-type="search" @confirm="queryFoodsByKeywordFn"  class="search_input">

				</view>
				<view class="storeBottom">
					<view class="left">
						<!-- <view class="title">点菜</view> -->
						<scroll-view class="menuClassList" :style="{ height: 'calc(100vh - ' +couponsHeight + 'px - 630rpx)'}"  scroll-y >
							<view @click="setMemuClass(item)"
								:class="['menuClass',foodTypeName == item ? 'active' : '']"
								v-for="(item,index) in storeDetail.foodTypes">
								{{item}}
							</view>
						</scroll-view>
					</view>
					<scroll-view class="right" :style="{ height: 'calc(100vh - ' +couponsHeight + 'px - 630rpx)'}" scroll-y>
						<template>
							<view class="dish_title">
								{{}}
							</view>
							<view class="dish" v-for="(items,indexs) in  groupedFood ">
								<view class="dish_img" @click="showDish(items)">
									<image :src="items.image"></image>
								</view>
								<view class="dish_right">
									<view class="dish_name">{{items.foodName}}</view>
									<view class="dish_num">
										<view class="money"><text>￥</text>{{ items.showPrice }}</view>  
										
										<view class="specConetnt" v-if="items.specification.length">
											<view class="selSpec" @click="showSpecAlert(item,items)">
												<view class="">选规格</view>
											</view>
											<view class="num" v-if="items.count > 0">{{ items.count }}</view>
										</view>
										<view class="showInput" v-else>
											<view class="operation" v-if="items.count" @click="changeShopNum('down',items,{storeId,storeName:storeDetail.storeName},siteAddrId)">
												<image src="/static/minus.jpg"></image>
											</view>
											<text class="count" v-if="items.count">{{items.count}}</text>
											<view class="operation" @click="changeShopNum('add',items,{storeId,storeName:storeDetail.storeName},siteAddrId)">
												<image src="/static/add.png"></image>
											</view>
										</view>
									</view>
								</view>
							</view>
						</template>
					</scroll-view>
				</view>
			</view>
		</view>
		<!-- 规格 -->
		<specBox ref="specBox" :addressId="siteAddrId" @getShopCar="getShopCar" :storeDetail="storeDetail" :specInfo="specInfo"></specBox>
		<!-- 小程序登录 -->
		<login @loginSuccess="loginSuccess" :auth.sync="auth"></login>
		<!-- 购物车 -->
		<shopCar :siteAddrId="siteAddrId" ref="shopCar" @setMustPurchase="setMustPurchase"></shopCar>
		<!-- 菜品详情 -->
		<dishDetails ref="dishDetails" :dish="dish"></dishDetails>
	</view>
</template>

<script>
	import MyMinix from '@/utils/minix/minix.js';
	import util from "@/utils/util.js";
	import {
		queryStoreDetail,
		queryFoodByType,
		queryFoodsByKeyword,
		addShoppingCart,
		removeShoppingCart,
		receiveCoupon
	} from "@/request/api.js";
	export default {
		mixins: [MyMinix],
		// name: "storeDetails",

		// 获取 vuex里的购物车信息
		computed: {
			shopCarInfo() {
				// console.log(66661);
				// console.log(this.shopCarInfo,'shopCarInfo');
				return this.$store.getters.getShopCarInfo
			},
			// //优惠券高度
			// getScrollHeight(){
			//   return {"minHeight":`calc(100vh - 645 + ${this.couponsHeight}* 2rpx`}
			// },
		},
		// 数据监听
		watch: {
			// 购物车数据改变了
			shopCarInfo: {
				handler(val) {
					// console.log(6666,val);
					this.setCount(val.shopCarList);
				},
				deep: true, //深度监听 
				immediate: true //第一次设置数据触发

			}
		},

		data() {
			return {
				storeDetail: {}, //店铺详情
				keyword: '', //输入框搜索菜名
				foodTypeName: '全部', //分类名称
				pageNo: 1, //分页参数
				pageSize: 100, //页码
				menuClass: [], //菜品分类
				groupedFood: [], //菜品列表
				specInfo: {}, //菜品规格
				siteAddrId: '', //大厦地址id
				storeId: '', //店铺id
				shopCarList: [], //购物车列表
				auth: false, //授权弹窗状态
				menuButton: {},
				dish:{},
				couponsHeight:0,
				mustPurchase:0,
				// isSearch:false
			};
		},
		onLoad(options) {
			this.storeId = options.storeId;
			this.siteAddrId = options.siteAddrId;
			this.mustPurchase = options.mustPurchase;
		},
		async onShow() {
			this.menuButton = util.getMenuButton()
			await this.initData();
			// this.$nextTick(()=>{
			// 	let shopCarInfo = this.$store.getters.getShopCarInfo
			// 	this.setCount(shopCarInfo.shopCarList)
			// })
			
			// if(this.mustPurchase == 1 && util.isMustPurchase(this.shopCarInfo.shopCarList) != null){
			// 	uni.showToast({
			// 		title: `${this.storeDetail.storeName}店铺没有选择必点菜品！`,
			// 		icon: 'none',
			// 		duration:3000
			// 	})
			// 	this.setMustPurchase();
			// }
		},
		methods: {
			 async setMustPurchase(data){
				if(data && this.storeId != data.storeId){
					this.storeId = data.storeId;
					await this.initData();
					this.setMustPurchases();
				}else{
					this.setMustPurchases();
				}
				
			},
			setMustPurchases(){
				console.log(this.storeDetail,'this.storeDetail');
				this.$nextTick(()=>{
					let foodTypeName = this.storeDetail.foodTypes.find(item=> item.indexOf('必点') != -1)
					if(foodTypeName){
						this.foodTypeName = foodTypeName;
						this.groupedFood = this.storeDetail.groupedFoods[foodTypeName];
					}
				})
			},
			back(){
				uni.navigateBack();
			},
			// 初始化数据 
			async initData() {
				await this.queryStoreDetailFn();
				let token = uni.getStorageSync('token');
				if (token) {
					await this.getShopCar();
				}
			},
			// 显示菜品详情
			showDish(data){
				this.dish = data;
				console.log(this.dish,'dish');
				this.$refs.dishDetails.showPop();
			},
			// 获取购物车的菜品数量，并显示到页面
			setCount(nval) {
				// nval?.forEach(item => {
				// 	for (var key in this.storeDetail.groupedFoods) {
				// 		this.storeDetail.groupedFoods[key].forEach(items1 => {
				// 			if (items1.foodId == item.foodId) {
				// 				items1.count = item.count;
				// 			}
				// 		})
				// 	}
				// })

				nval?.forEach(items => {
					this.groupedFood?.forEach(items1 => {
						let items2 = nval.map(item => item).filter(item => item.foodId ==
							items1.foodId)
						if (items1.count == 1 && !items2) {
							this.$set(items1, 'count', 0)
						}
						if (items2.length) {
							this.$set(items1, 'count', items2.reduce((num, item) => num + item.count,
								0))
						}
					})
				})
			},
			// 登录成功，隐藏登录弹窗，初始化店铺信息
			loginSuccess() {
				this.auth = false;
				this.initData();
			},
		
			// 获取优惠券高度s
			getCouponsHeight(){
				this.$nextTick(()=>{
					uni.createSelectorQuery().selectAll('.coupons').boundingClientRect(data => {
							this.couponsHeight = data[0]?.height
					}).exec()
				})
			},
			// 点击左侧菜单分类
			setMemuClass(name) {
				this.foodTypeName = name
				this.groupedFood = this.storeDetail.groupedFoods[name];
				this.setCount(this.shopCarInfo.shopCarList);
				// this.queryFoodByTypeFn();
			},
			// 获取店铺详情 左侧菜单分类
			
			async queryStoreDetailFn() {
				let userInfo = uni.getStorageSync('userInfo');
				let res = await queryStoreDetail({
					method: "GET",
					data: {
						// siteId: this.siteAddrId,
						companyId:userInfo.companyId,
						menuId:userInfo.menuId,
						storeId: this.storeId
					},
				})
				
				// if (res.code == 200) {
				 	let result = res.data;
					// result.foodTypes.unshift('选品');
					// let xuanpin = [];
					
					for (var key in result.groupedFoods) {
						let item =  result.groupedFoods[key].map(items => {
							items.count = 0;
							return items;
						})
						console.log(item,'item');
						// xuanpin.push(...item)
					}
					// result.groupedFoods['选品'] = xuanpin; 
					let {groupedFoods,mustSelectedFoods} = result;
					this.storeDetail = result
					// let groupedFood = result.groupedFood
					this.groupedFood = groupedFoods[this.foodTypeName];
					
					this.setCount(this.shopCarInfo.shopCarList);
					this.getCouponsHeight();
					
					util.setMustSelectedFoods(result,mustSelectedFoods);
					
				// }
			},
			// 根据菜单分类获取菜单列表 弃用
			async queryFoodByTypeFn() {
				let res = await queryFoodByType({
					method: "GET",
					data: {
						siteId: this.siteAddrId,
						storeId: this.storeId,
						foodTypeName: this.foodTypeName,
						pageNo: this.pageNo,
						pageSize: this.pageSize
					},
				})

				this.groupedFood = res.result.groupedFood;

			},

			// 店铺内根据搜索条件返回符合条件的菜品  
			async queryFoodsByKeywordFn() {
				let userInfo = uni.getStorageSync('userInfo');
				let res = await queryFoodsByKeyword({
					method: "GET",
					data: {
						siteId: this.siteAddrId,
						// storeId: this.storeId,
						// companyId:userInfo.companyId,
						// menuId:userInfo.menuId,
						storeId: this.storeId,
						keyword: this.keyword,
						pageNo: this.pageNo,
						pageSize: this.pageSize
					},
				})
				if (res.code == 200) {
					
					// this.storeDetail.groupedFoods[this.foodTypeName] = res.result.foods;
					this.groupedFood = res.result.foods;
					this.setCount(this.shopCarInfo.shopCarList);
				}
			},
			// 领取优惠券
			async claimCoupons(item, items) {
				let token = uni.getStorageSync('token');
				if (!token) {
					this.auth = true;
					return;
				}
				if (items.received) {
					uni.showToast({
						title: '已经领取，不能重复领取!',
						icon: 'none'
					})
					return;
				}
				let res = await receiveCoupon({
					method: "POST",
					data: {
						"siteId": this.siteAddrId,
						"storeId": item.storeId,
						"couponId": items.couponId,
					},
				})
				let isSuccess = res.code == 200;
				uni.showToast({
					title: isSuccess ? '领取成功!' : res.message,
					icon: isSuccess ? 'success' : 'none'
				})
				isSuccess && this.$set(items, 'received', true);
			},

			//展示商品规格选择弹窗
			showSpecAlert(item, foodItem) {
				let token = uni.getStorageSync('token');
				if (!token) {
					this.auth = true;
					return;
				}
				// 跟首页的规格同步
				foodItem.specifications = foodItem.specification
				this.specInfo = foodItem
				this.$nextTick(() => {
					this.$refs.specBox.showSpec()
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.store {
		// background-color: #eee;
		background: linear-gradient(0.45deg, #f5f5f5 6.52%, #ec6025 58.65%, #ec6025 98.93%);
		overflow: hidden;

		.back {
			position: fixed;
			left: 30rpx;
			z-index: 10;
		}
		.storeDetailsBg{
			width:100%;
			image{
				width:100%;
				height:250rpx;
			}
		}
	}

	// 店铺详情 内容部分
	.storeContent {
		// position: absolute;
		margin-top: 200rpx;
		position: fixed;
		top:0;
		width:100%;
		
		// bottom: 0;
	}

	// 店铺详情 头部
	.storeTop {
		padding: 30rpx 30rpx 15rpx ;
		width: calc(100% - 60rpx);
		@include flexs(space-between, flex-start);
		z-index: 100;
		background: #fff;
		border-radius: 40rpx 40rpx 0px 0px;
		// border-radius: 10rpx;
		// box-shadow: 0 0 5rpx rgba(0, 0, 0, .2);
		

		//店铺logo
		.logo {
			width: 144rpx;
			height: 144rpx;
			// margin-top: -60rpx;
			position: absolute;
			top:-50rpx;
			right:30rpx;
			border-radius: 20rpx;
			box-shadow: 0 0 10rpx rgba(0, 0, 0, .2);
		}

		// 店铺名称 简介
		.right {
			// justify-content: space-around
			@include flexs(space-around, flex-start);
			flex-direction: column;
			margin-left: 15rpx;

			// 名称
			.name {
				width:calc(100% - 155rpx);
				font-size: 48rpx;
				font-weight: 600;

			}

			// 简介
			.des {
				display: flex;
				font-size: 22rpx;
				color: #999;
				margin: 20rpx 0;

				>view {
					margin-right: 30rpx;

					&:first-child {
						margin-top: -4rpx;
					}

					&:last-child {
						color: #666;
					}
				}

				text {
					color: #FF1010;
					margin-left: 10rpx;
				}
			}

			// 优惠券
			.coupons {
				font-size: 22rpx;
				color: #fff;
				@include flexs(space-between, center);
				flex-wrap: wrap;

				&>view {
					background: #FC651C;
					margin:0 10rpx  15rpx 0;
					padding: 5rpx 10rpx;
					border-radius: 5rpx;
					white-space: nowrap;

					text {

						padding-left: 10rpx;
						margin-left: 10rpx;
						border-left: 1rpx solid #fff;
					}
				}

				.received {
					background: #ccc;
				}
			}
		}
	}

	// 店铺详情 搜索菜品
	.search {
		@include flexs(space-between, center);
		margin: 0 30rpx 30rpx;
		border-radius: 30rpx;
		background: #EEEEEE;
		height: 65rpx;
		line-height: 65rpx;

		input {
			flex: 1;
			padding: 0 20rpx;
		}

		view {
			@include flexs(center, center);
			text-align: center;
			padding: 10rpx 0 0 15rpx;
		}
	}

	// 店铺详情 菜品分类 、菜品
	.storeBottom {
		width: 100%;
		background: #fff;
		@include flexs(space-between, flex-start);

		//菜品分类
		.left {

			width: 200rpx;

			.title {
				padding: 20rpx 25rpx 0;
				font-size: 28rpx;
			}

			.menuClassList {
				// height: calc(100vh - 645rpx);
				
				background: #F6F6F6;
			}

			.menuClass {
				padding: 20rpx 16rpx;
				font-size: 28rpx;
				color: #666666;
				text-align: center;

				&.active {
					color: #FE3630;
					position: relative;
					// &::after{
					// 	content: '';
					// 	width:6rpx;
					// 	height:30rpx;
					// 	background: #35AA4C;
					// 	position: absolute;
					// 	top:50%;
					// 	left:10rpx;
					// 	transform: translateY(-50%);
					// }
				}
			}
		}

		// 菜品
		.right {
			// margin-top: 60rpx;
			width: calc(100% - 202rpx);
			// height: calc(100vh - 645rpx);
			
			.dish_title {
				font-size: 28rpx;
				color: #FE3630;
				font-weight: 600;
				padding: 20rpx 15rpx 0;
			}

			.dish {
				@include flexs(space-between, stretch);
				padding: 30rpx 50rpx 0 20rpx;
				&:last-child{
					padding-bottom:30rpx;
				}
				&_img {
					width: 160rpx;
					height: 160rpx;
					margin-right: 20rpx;
					border-radius: 20rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				&_name {
					font-size: 28rpx;
					font-weight: 600;
				}

				&_right {
					width: calc(100% - 135rpx);
					@include flexs(space-between, flex-start);
					flex-direction: column;
				}

				&_num {
					width: 100%;
					@include flexs(space-between, flex-end);
				}

				.money {
					color: #EC2020;
					font-size: 40rpx;

					text {
						font-size: 28rpx;
					}
				}

				.specConetnt {
					font-size: 22rpx;
					background: #EB5B1E;
					border-radius: 4px;
					padding: 5rpx 10rpx;
					color: #fff;
					position: relative;
				}

				.num {
					width: 30rpx;
					height: 30rpx;
					font-size: 20rpx;
					border-radius: 50%;
					background-color: #f60000;
					position: absolute;
					right: -10rpx;
					top: -10rpx;
					line-height: 30rpx;
					text-align: center;
					color: #fff;
				}
			}

			// .showInput {
			// 	width: 50%;
			// 	@include flexs(space-between, center);
			// 	color: #000000;
			// 	border-radius: 50rpx;
			// 	border: 1px solid #eee;

			// 	view {
			// 		width: 55rpx;
			// 		height: 50rpx;
			// 		line-height: 45rpx;
			// 		text-align: center;
			// 		font-size: 26px;
			// 	}

			// 	input {
			// 		flex: 1;
			// 		text-align: center;
			// 	}
			// }
		}
	}
</style>